import React, { useState } from 'react';
import { Card, Form, Input, Button, Alert } from "antd";
import { useDispatch } from "react-redux";
import { fetchLogin } from "../../store/modules/user.js";
import { useNavigate } from "react-router-dom";

const Index = () => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState(''); // 添加错误状态
    const dispatch = useDispatch();
    const navigate = useNavigate();

    const onFinish = async (values) => {
        try {
            await dispatch(fetchLogin(values));
            navigate('/layout');
        } catch (err) {
            setError(err.response.data.error); // 更新错误状态
        }
    }

    return (
        <div>
            <Card title="登录">
                <Form onFinish={onFinish}>
                    <Form.Item
                        label="用户名"
                        name="username"
                        rules={[{ required: true, message: '请输入用户名' }]}>
                        <Input
                            type="text"
                            value={username}
                            onChange={(e) => setUsername(e.target.value)}
                        />
                    </Form.Item>
                    <Form.Item
                        label="密码"
                        name="password"
                        rules={[{ required: true, message: '请输入密码' }]}>
                        <Input
                            type="password"
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                        />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" size="large" block>登录</Button>
                    </Form.Item>
                </Form>
                {error && <Alert message={<p style={{ color: 'red' }}>{error}</p>} type="error" />}
            </Card>
        </div>
    );
};

export default Index;

